import { Player, world, RawMessage } from "@minecraft/server";
import { MessageFormData } from "@minecraft/server-ui";
import { getModId, getModName } from "../index";

/**
 * Post a message to world.
 * @param message Body of the message.
 * @param players Players that will get the message
 * @param sendToWorld If specified, will send the message to world.
 * @param postByForm If specified, will send the message by ui.
 */
export function postMessage(
  message: string | RawMessage,
  players: Player[],
  sendToWorld?: boolean,
  postByForm?: boolean,
): void {
  if (postByForm) {
    const FORM = new MessageFormData()
      .title(getModName())
      .body(message)
      .button1({ translate: "gui.close" })
      .button2({ translate: "gui.confirm" });
    players.forEach((player) => {
      FORM.show(player);
    });
  } else {
    players.forEach((player) => {
      player.sendMessage("[" + getModId() + "]" + message);
    });
  }
  if (sendToWorld) {
    world.sendMessage("[" + getModId() + "]" + message);
  }
}

/**
 * Send a welcome message.
 * @param message The welcome message to send.
 */
export function sendWelcomeMessage(
  message: string | RawMessage | (string | RawMessage)[],
): void {
  world.afterEvents.playerSpawn.subscribe((event) => {
    if (event.initialSpawn) {
      event.player.sendMessage(message);
    }
  });
}
